<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<title>文件列表</title>
<script type="text/javascript">
function add(){
	window.location='file/edit';
}

function del(id){
	if(confirm('是否要删除这条数据？')){
		$.post('file/delete',{id:id},function(data){
			if(data.success){
				refreshTable();
			}else{
				alert(data.msg);
			}
		})
	}
}

function edit(id){
	window.location="file/edit?id="+id;
}

function edit2(id){
	var dialog=$('<div style="display:none;"/>');
	$('body').append(dialog);
	dialog.dialog({
		autoOpen:false,
		title:'编辑',
		modal:true,
		width:400,
		buttons:[{
			text:'保存',
			click:function(){
				var form=dialog.find('form');
				var params= new FormData(form[0]);
				$.ajax({
					url:'file/save2',
					type:'POST',
					data:params,
					contentType:false,
					processData:false,
					success:function(data){
						refreshTable();
						dialog.remove();
					},
					error:function(){
						alert('网络连接失败...');
					}
				})
			}
		},{
			text:'关闭',
			click:function(){
				dialog.remove();
			}
		}]
	});
	dialog.load('file/edit2',{id:id},function(){
		dialog.dialog('open');
	})
}

function refreshTable(){
	$.post('file/list',function(data){
		var tbody=$('#tbody');
		tbody.empty();
		for(var i=0;i<data.length;i++){
			var file=data[i];
			var tr=$('<tr/>');
			tr.append($('<td/>').text(file.id));
			tr.append($('<td/>').html(file.title));
			tr.append($('<td/>').html(file.filename));
			tr.append($('<td/>').append($('<button/>').attr('onclick','edit2('+file.id+')').html('修改')));
			tr.append($('<td/>').append($('<button/>').attr('onclick','del('+file.id+')').html('删除')));
			tr.append($('<td/>').append($('<a/>').attr('href','file/download?id='+file.id).html('下载')));
			tbody.append(tr);
		}
	});
}

$(function(){
	refreshTable();
})
</script>

<style type="text/css">
table {
	border-collapse: collapse;
	width: 800px; 	
}

td,th {
	padding: 8px 15px;
	text-align: center;
}

button {
	padding: 5px 20px;
}
</style>
<body>
<!-- <p><button type="button" onclick="add()">新增</button></p> -->
<p><button type="button" onclick="edit2()">新增</button></p>
<table border="1">
	<thead>
		<tr>
			<th>序号</th>
			<th>文件标题</th>
			<th>文件名</th>
			<th colspan="3">操作</th>
		</tr>
	</thead>
	<tbody id="tbody"></tbody>
</table>
</body>
